﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;

namespace Powersource.WebApp
{
    public class EventLogWriter : IDisposable
    {
        EventLog Log;

        public EventLogWriter()
        {
            Log = new EventLog();
            Log.Source = "ASP.NET 4.0.30319.0";
            Log.Log = "Application";
        }

        public string EntryAppend { get; set; }

        public void Error(Exception exc, string format, params object[] args)
        {
            var s=String.Format(format,args);
            var exstr = "No exception attached";
            if (exc!=null) exstr=exc.ToString();
            var msg=string.Format("{0} \r\nException: {1} \r\n\r\n-------\r\n{2}",s,exstr,EntryAppend);
            Log.WriteEntry(msg, EventLogEntryType.Error);
        }

        public void Warn(Exception exc, string format, params object[] args)
        {
            var s = String.Format(format, args);
            var exstr = "No exception attached";
            if (exc != null) exstr = exc.ToString();
            var msg = string.Format("{0} \r\nException: {1} \r\n\r\n-------\r\n{2}", s, exstr, EntryAppend);
            Log.WriteEntry(msg, EventLogEntryType.Warning);
        }

        public void Info(string format, params object[] args)
        {
            var s = String.Format(format, args);
            
            var msg = string.Format("{0}\r\n\r\n-------\r\n{2}", s,  EntryAppend);
            Log.WriteEntry(msg, EventLogEntryType.Information);
        }

        public void Dispose()
        {
            Dispose(true);
        }

        private void Dispose(bool p)
        {
            if (!IsDisposed)
            {
                if (Log != null)
                {
                    Log.Dispose();
                    Log = null;
                }
                IsDisposed = true;
            }
        }

        public bool IsDisposed
        {
            get;
            private set;
        }
    }
}